﻿using System;
using System.Collections.Generic;
using System.Text;
using FunctionalCLR;
using FunctionalCLR.Core;
using FunctionalCLR.Core.Function;

namespace FunctionalCLR.Shell {
    public class ContextUserDefinedFunctionNode : UserDefinedFunctionNode {

        public IContext Context {
            get;
            set;
        }

        public override object Evaluate() {
            double[] parameterValue = new double[this.Children.Count];

            for(int index = 0; index < this.Children.Count; index++) {
                parameterValue[index] 
                    = Convert.ToDouble(this.Children[index].Evaluate());
            }

            string expr = base.FuncBody;
            for(int index = 0; index < this.Parameters.Length; index++) {
                expr = FunctionalCLR.Core.Utils.ReplaceString(
                    this.Parameters[index], 
                    parameterValue[index].ToString(), 
                    expr);
            }

            Node root = ((Context)Context).Parse(expr);
            object result = root.Evaluate();

            return result;
        }

        public override object Accept(IVisitor visitor) {
            return visitor.Visit(this);
        }
    }
}
